//
// Created by dong on 2025/10/21.
//

#include "SMenu.h"

#include "Swindow.h"

SMenu::SMenu(Swidget* parent):SMenu("menu",parent)
{
}

SMenu::SMenu(const string& text, Swidget* parent):Swidget(parent)
{
    m_data->title = text;
    m_text = text;
    m_data->w = 60;
    m_data->h  =30;
}

SAction* SMenu::addAction(const string& text)
{
    return SMenu::addAction(new SAction(text,this));
}

SAction* SMenu::addAction(SAction* act)
{
    m_action.push_back(unique_ptr<SAction>(act));
    return act;
}

void SMenu::paintEvent(SDL_Event* msg)
{
    Swidget::paintEvent(msg);
    TTF_Font* font = TTF_OpenFont("../simkai.ttf",20);
    SDL_Surface* surface = TTF_RenderUTF8_Blended(font,m_text.c_str(),m_data->textColor);
    SDL_Texture* temp = SDL_CreateTextureFromSurface(Swindow::render,surface);
    int tw  =surface->w;
    int th = surface->h;
    SDL_Rect dst={m_data->x +(m_data->w-tw)/2,m_data->y+(m_data->h-th)/2,tw,th};
    SDL_RenderCopy(Swindow::render,temp,NULL,&dst);
    SDL_FreeSurface(surface);
    TTF_CloseFont(font);

}

void SMenu::mousePressEvent(SDL_Event* msg)
{
    if (Swidget::contains(msg->motion.x,msg->motion.y))
    {
        for (int i=0;i<m_action.size();i++)
        {
            m_action[i]->setpos(m_data->x,m_data->y+m_data->h*(i+1));
            m_action[i]->setvisible(true);
            m_action[i]->setfocus(false);

        }
    }else
    {
        for (int i=0;i<m_action.size();i++)
        {
            if (!m_action[i]->contains(msg->motion.x,msg->motion.y))
            {
                m_action[i]->setvisible(false);
            }

        }
    }
}

void SMenu::mouseMoveEvent(SDL_Event* msg)
{
   if (Swidget::contains(msg->motion.x,msg->motion.y))
   {
       m_data->isFocus=true;
   }else
   {
       m_data->isFocus = false;
   }
}
